package com.widget;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;

import android.util.Log;

import com.google.ase.Exec;


class MyThread implements Runnable {

	   private DataInputStream stdin;
	   private ParseStreaming parser;
	   private final static int BUFF_LEN=1024;
	   private byte []buffer;
	   public MyThread(DataInputStream in,ParseStreaming p) {
	       stdin = in;
	       parser = p;
	       buffer = new byte[BUFF_LEN];
	   }

	   public void run() {
		   try {
           	String out="";
           	int read=0,bytesRead=0;
               while(true) {
               	//terminate when rsync is not there
               	read = stdin.read(buffer);
   				
   				bytesRead +=read;
   				out = new String(buffer, 0, read);
   				int retcode = parser.parseString(out);
   				if(retcode==0)
   					break;
   				Log.i("Reader",out);
               }
               } catch (IOException e) {
               }
		   Log.d("THREAD","Exiting Thread :)");
	   }
}
public class ManageProcess {

	private FileDescriptor shellFd;
	private final static int BUFF_LEN=1024;
	private DataInputStream stdin;
	private DataOutputStream stdout;
	private byte []buffer;
	private Hashtable<String,String> runningProcesses = new Hashtable<String,String>();
	Runnable fetchContent;
	Thread current;
	ManageProcess() {
		int[] pids = new int[1];
		try {
			shellFd = Exec.createSubprocess("/system/bin/sh", "-", null, pids);
		} catch (Exception e) {
			e.printStackTrace();
		}
		final int shellPid = pids[0];	
		FileInputStream is = new FileInputStream(shellFd);
		stdin = new DataInputStream(is);
		FileOutputStream os = new FileOutputStream(shellFd);
		stdout = new DataOutputStream(os);
		buffer = new byte[BUFF_LEN];
		current = null;
	
	}
	
	void setParser(ParseStreaming parser){
		//if(current != null)
		//{
			//current.stop();
		//}
		fetchContent = new MyThread(stdin,parser);
		current = new Thread(fetchContent);
		current.start();
	}
	
	
	
	void acquireRoot() {
		executeCmd("su");
	}
	void close() {
		try {
			stdout.close();
			stdin.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	String readCmd(String out) {
		int bytesRead = 0;
		while(true){
				
			
				int read;
				try {
					read = stdin.read(buffer);
				
				bytesRead +=read;
				out += new String(buffer, 0, read);
				if(read<BUFF_LEN){
	        
					break;
				}
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			
		}
	return out;
	}
	
	String executeCmd(String command) {
		String out="";
		try {
			
			stdout.writeBytes(command+"\n");
			stdout.flush();
			
			
		
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return out;
		
	}
	
	   public ArrayList<String> readLinesFromFile(String filename) {
	    	String line = null;
	    	BufferedReader br = null;
	    	InputStream ins = null;
	    	ArrayList<String> lines = new ArrayList<String>();
	    	File file = new File(filename);
	    	if (file.canRead() == false)
	    		return lines;
	    	try {
	    		ins = new FileInputStream(file);
	    		br = new BufferedReader(new InputStreamReader(ins), 8192);
	    		while((line = br.readLine())!=null) {
	    			lines.add(line.trim());
	    		}
	    	} catch (Exception e) {
	    		Log.d("SYNC", "Unexpected error - Here is what I know: "+e.getMessage());
	    	}
	    	finally {
	    		try {
	    			ins.close();
	    			br.close();
	    		} catch (Exception e) {
	    			// Nothing.
	    		}
	    	}
	    	return lines;
	    }
	   
	boolean isProcessRunning(String processName) throws Exception {
		boolean processIsRunning = false;
    	//Hashtable<String,String> tmpRunningProcesses = new Hashtable<String,String>();
    	File procDir = new File("/proc");
    	FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                try {
                    Integer.parseInt(name);
                } catch (NumberFormatException ex) {
                    return false;
                }
                return true;
            }
        };
    	File[] processes = procDir.listFiles(filter);
    	for (File process : processes) {
    		String cmdLine = "";
    		do{
    		ArrayList<String> cmdlineContent = this.readLinesFromFile(process.getAbsoluteFile()+"/cmdline");
    			if (cmdlineContent != null && cmdlineContent.size() > 0) {
    				cmdLine = cmdlineContent.get(0);
    				if (cmdLine.contains(processName)) {
    	    			processIsRunning = true;
    	    		}
    			}
    			else
    			{
    				processIsRunning = false;
    			}
    		
    		
    	}while(processIsRunning);
    	}
    	// Overwriting runningProcesses
    	//this.runningProcesses = tmpRunningProcesses;
    	return processIsRunning;
	}
		
	

}
